<?php



class oauth extends snoopy
{
	var $appid;
	
	var $appkey;
	/* 版本号，请固定使用1.0 */
	var $oauth_version = '1.0';
	
	function __construct($appid,$appkey)
	{
		$this->appid = $appid;
		$this->appkey = $appkey;
		
	}
	
	function moren()
	{
		$array['oauth_nonce'] = $this->nonce();
		$array['oauth_timestamp'] = time();
		$array['oauth_signature_method'] = 'HMAC-SHA1';
		$array['oauth_version'] = $this->oauth_version;
		$array['oauth_consumer_key'] = $this->appid;

		return $array;
	}
	
	/* 随机字符串，所有oauth_nonce请使用int型值 */
	function nonce()
	{
		return mt_rand();//time();
	}
	
	
	/* HMAC 签名算法 */
	function singn($url,$method='GET',$array=array(),$token='')
	{

		$array = array_merge($this->moren(),$array);
		
		uksort($array, 'strcmp');
		
		foreach ($array as $key=>$val)
		{
			$base_string[] = urldecode($key).'%3D'.$this->urlencode_rfc3986(trim($val));
		}

		$base_string = implode('%26',$base_string);
		
		$base_string =  $method.'&'.rawurlencode($url).'&'.$base_string;
		
		
		return  base64_encode(hash_hmac('SHA1', $base_string, $this->appkey.'&'.$token, true));
	}
	
	/* HTTP请求 */
	function http($url,$method='GET',$array=array(),$file='')
	{ 

		$array['oauth_signature'] = $this->singn($url,$method,$array);

		if ($method == 'GET')
		{
			foreach ($array as $key=>$val)
			{
				$f[] = $key.'='.urlencode($val);
			}
			$url .= '?'.implode('&',$f);
			
			$this->fetch($url);
		}
		else
		{
			$array['oauth_signature'] = $this->urlencode_rfc3986($array['oauth_signature']);
			
			foreach ($array as $key=>$val)
			{
				$array2[$key] = urldecode(trim($val));
			}
			
			$array = $array2;
			unset($array2);
			

			$this->submit($url,$array,$file);
		}

		return $this->results;
	}
	
	function token($url)
	{

		$reset =  $this->http('http://openapi.qzone.qq.com/oauth/qzoneoauth_request_token','GET',$this->moren());
		
		return $this->token_array($reset);
	}
	/* 转换TOKEN */
	function token_array($array)
	{
		$array = explode('&',$array);
		foreach ($array as $val)
		{
			$val = explode('=',$val);
			$arrays2[$val[0]] = $val[1];
		}
		return $arrays2;
	}
	
	function urlencode_rfc3986($input)
	{ 
        if (is_array($input))
		{ 
            return array_map(array('oauth', 'urlencode_rfc3986'), $input); 
        } 
		else if (is_scalar($input))
		{ 
            return str_replace( 
                '+', 
                ' ', 
                str_replace('%7E', '~', rawurlencode($input)) 
            ); 
        }
		else
		{ 
            return ''; 
        } 
    } 
}
?>